package com.guxingke.gblog.controller.front;

import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.guxingke.gblog.controller.BaseController;
import com.guxingke.gblog.dmo.FriendLink;
import com.guxingke.gblog.dto.ArticleDto;
import com.guxingke.gblog.dto.ArticleLiteDto;
import com.guxingke.gblog.dto.MsgDto;
import com.guxingke.gblog.util.PageBean;
import com.guxingke.gblog.util.PageUtil;
import com.guxingke.gblog.util.PropertiesUtil;
import com.guxingke.gblog.util.StringUtil;

@Controller
public class HomeController extends BaseController {

	@RequestMapping("/home")
	public String home(HttpServletRequest request, HttpServletResponse response) {

		ServletContext application = request.getSession().getServletContext();

		List<ArticleLiteDto> recentArticles = articleService
				.getRecentArticles();
		List<MsgDto> recentMsgs = msgService.getRecentMsgs();
		List<FriendLink> friendLinks = friendLinkService.getFriendLinks();
		application.setAttribute("recentArticles", recentArticles);
		application.setAttribute("recentMsgs", recentMsgs);
		application.setAttribute("friends", friendLinks);

		String page = request.getParameter("page");

		if (StringUtil.isEmpty(page)) {
			page = "1";
		}

		List<ArticleDto> articles = null;
		PageBean pageBean = new PageBean(Integer.parseInt(page),
				Integer.parseInt(PropertiesUtil.getValue("pageSize")));
		articles = articleService.getArticles(pageBean);
		int total = articleService.count();
		String pageCode = PageUtil.getPagation("home.do",total, Integer.parseInt(page),
				Integer.parseInt(PropertiesUtil.getValue("pageSize")));

		String mainPage = "article/list.jsp";

		request.setAttribute("articles", articles);
		request.setAttribute("pageCode", pageCode);
		request.setAttribute("mainPage", mainPage);

		return "forward:WEB-INF/template/home.jsp";
	}
}
